<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: t('sys.device.bindCode'),
                tooltip: t('sys.device.bindCode'),
                onClick: handleCreate.bind(null, record),
              },
              {
                label: t('sys.device.unbundle'),
                tooltip: t('sys.device.unbundle'),
                onClick: handlerelieve.bind(null, record),
              },
              {
                label: t('sys.device.setanote'),
                tooltip: t('sys.device.setanote'),
                onClick: handleSetRemark.bind(null, record),
              },
              {
                label: t('sys.device.historicaltask'),
                tooltip: t('sys.device.historicaltask'),
                onClick: handleView.bind(null, record),
              },
              {
                label: t('sys.device.examine'),
                tooltip: t('sys.device.examineerror'),
                onClick: openView.bind(null, record),
              },
              {
                label: t('sys.device.errorSubmit'),
                tooltip: t('sys.device.errorSubmit'),
                onClick: handleReportAbnormal.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <RemarkModal @register="registerRemarkModal" @success="handleRemarkSuccess" />
    <Errview @register="registerModalError" />
    <phaseView @register="registerphaseView" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watch } from 'vue';
  import { useModal } from '@/components/Modal';
  import { message } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    getdeviceAPI,
    updateRemarkAPI,
    unbindAuthorizationCodeApi,
    reportAbnormalAPI,
  } from '@/api/demo/device';
  import { PageWrapper } from '@/components/Page';
  import { columns } from './account.data';
  import { useGo } from '@/hooks/web/usePage';
  import AccountModal from './AccountModal.vue';
  import RemarkModal from './RemarkModal.vue';
  import Errview from './errview.vue';
  import { useWebSocketStore } from '@/store/modules/websocket';
  import phaseView from '.././questManage/TaskList/phaseView.vue';
  import { useI18n } from '@/hooks/web/useI18n';

  const webSocketStore = useWebSocketStore();

  const { t } = useI18n();
  defineOptions({ name: 'AccountManagement' });
  const total = ref(0);

  const tableTitle = computed(() => `${t('sys.device.title')} ${t('sys.configuration.common')} ${total.value} ${t('sys.configuration.strip')}`);
  const go = useGo();
  const searchInfo = reactive<Recordable>({});
  const [registerModal, { openModal }] = useModal();
  const [registerModalError, { openModal: openViewMOdal }] = useModal();
  const [registerRemarkModal, { openModal: openRemarkModal }] = useModal();
  const [registerphaseView, { openModal: openphaseView }] = useModal();
  const [registerTable, { reload, updateTableDataRecord, getDataSource }] = useTable({
    title: tableTitle,
    api: async (params) => {
      const result = (await getdeviceAPI(params)) as { items: any[]; total: number };
      total.value = result.total;
      return result;
    },
    rowKey: 'device',
    columns,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 200,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
    },
  });

  function handleCreate(record) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }
  function openView(record) {
    openViewMOdal(true, {
      record,
      isUpdate: true,
    });
  }
  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      const result = updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }

  function handleSetRemark(record) {
    openRemarkModal(true, {
      record,
    });
  }
  async function handlerelieve(record) {
    let value = await unbindAuthorizationCodeApi(record.device);
    if (value.code == 200) {
      message.success(t('sys.configuration.succesSubmit'));
      reload();
    }
  }
  async function handleRemarkSuccess(values) {
    await updateRemarkAPI({ id: values.id, owner: values.owner });
    reload();
  }

  function handleView(record: Recordable) {
    openphaseView(true, {
      routers: t('sys.device.title'),
      record,
    });
  }

  async function handleReportAbnormal(record) {
    try {
      const response = await reportAbnormalAPI(record.device);
      if (response.code === 200) {
        message.success(t('sys.device.anomalySuccessfully'));
        reload();
      } else {
        message.error(t('sys.device.anomalyErrorfully'));
      }
    } catch (error) {
      message.error(t('sys.device.anomalyErrorfully'));
    }
  }

  //监听store的数据
  watch(
    () => webSocketStore.$state,
    (newState, oldState) => {
      // 在这里可以执行一些操作，例如更新表格数据
      const recordList = newState.recordList;
      if (recordList && recordList.length > 0) {
        recordList.forEach((record) => {
          if (record.type == t('sys.device.title')) {
            const tableRecord = findTableRecordById(record.code);
            if (tableRecord) {
              updateTableDataRecord(tableRecord.device, { [record.key]: record.value });
            }
          }
        });
      }
    },
    { deep: true },
  );

  function findTableRecordById(id: string): Recordable | undefined {
    const tableData = getDataSource();
    const tableRecord = tableData.find((record) => record.device == id);

    return tableRecord;
  }
</script>
